package admin

import (
	"laohuo/dao"
	"laohuo/model"
	"net/http"

	"github.com/gin-gonic/gin"
)

type Warehouse struct{}

func (c *Warehouse) List(ctx *gin.Context) {
	params := struct {
		Page     uint
		Pagesize uint
	}{}
	if err := ctx.ShouldBindQuery(&params); err != nil {
		ctx.String(http.StatusBadRequest, err.Error())
		return
	}
	if params.Page == 0 {
		params.Page = 1
	}
	if params.Pagesize == 0 || params.Pagesize > 100 {
		params.Pagesize = 20
	}

	whs, err := dao.FetchWareHousesWithSKU(params.Page, params.Pagesize)
	if err != nil {
		ctx.String(http.StatusInternalServerError, err.Error())
		return
	}

	total, _ := dao.CountWarehouse()
	ctx.JSON(http.StatusOK, &struct {
		Total int
		Data  []*model.WarehouseDetail
	}{total, whs})
}

func (c *Warehouse) Export() {}

func (c *Warehouse) Analysis() {}

func (c *Warehouse) Input(ctx *gin.Context) {
	params := struct {
		SKUID uint
		Num   uint
	}{}
	if err := ctx.ShouldBindJSON(&params); err != nil {
		ctx.String(http.StatusBadRequest, err.Error())
		return
	}
	if params.SKUID == 0 || params.Num == 0 {
		ctx.String(http.StatusBadRequest, "参数错误")
		return
	}

	if _, err := dao.FetchSkuById(params.SKUID); err != nil {
		ctx.String(http.StatusInternalServerError, err.Error())
		return
	}

	wh, err := dao.InputWarehouse(params.SKUID, params.Num)
	if err != nil {
		ctx.String(http.StatusInternalServerError, err.Error())
		return
	}
	ctx.JSON(http.StatusOK, wh)
}

func (wh *Warehouse) Output(ctx *gin.Context) {
	params := struct {
		SKUID uint
		Num   uint
	}{}
	if err := ctx.ShouldBindJSON(&params); err != nil {
		ctx.String(http.StatusBadRequest, err.Error())
		return
	}

	if _, err := dao.FetchSkuById(params.SKUID); err != nil {
		ctx.String(http.StatusInternalServerError, err.Error())
		return
	}

	if wh, err := dao.OutputWarehouse(params.SKUID, params.Num); err != nil {
		ctx.JSON(http.StatusInternalServerError, err.Error())
	} else {
		ctx.JSON(http.StatusOK, wh)
	}
}

func Bills(ctx *gin.Context) {
	params := struct {
		Page     uint
		Pagesize uint
	}{}
	if err := ctx.ShouldBindQuery(&params); err != nil {
		ctx.String(http.StatusBadRequest, "")
	}

	whb, err := dao.FetchWarehouseBill(params.Page, params.Pagesize)
	if err != nil {
		ctx.JSON(http.StatusOK, err)
	}

	ctx.JSON(http.StatusOK, whb)
}
